package com.demomaster.quickcompat.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.demomaster.quickcompat.R;
import com.demomaster.quickcompat.util.QDBitmapUtil;

/**
 * @author squirrel桓
 * @date 2018/11/20.
 * description：
 */
public class RatingBar extends androidx.appcompat.widget.AppCompatRatingBar {

    public RatingBar(Context context) {
        super(context);
        init(null);
    }

    public RatingBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public RatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private int backResourceId = -1;//背景色
    private int frontResourceId;//前景色
    private boolean useCustomDrawable = false;//0,颜色，true.图片资源
    private boolean isFloat = true;//0,float，1.int

    /**
     * 设置背景资源
     *
     * @param backResourceId 0为空
     */
    public void setBackResourceId(int backResourceId) {
        this.backResourceId = backResourceId;
        setCustomDrawable();
    }

    /**
     * 设置前景资源
     *
     * @param frontResourceId
     */
    public void setFrontResourceId(int frontResourceId) {
        this.frontResourceId = frontResourceId;
        setCustomDrawable();
    }

    private void setCustomDrawable() {
        setUseCustomDrawable(backResourceId != 0 || frontResourceId != 0);
    }

    /**
     * 设置资源类型
     *
     * @param useCustomDrawable
     */
    public void setUseCustomDrawable(boolean useCustomDrawable) {
        this.useCustomDrawable = useCustomDrawable;
    }

    /**
     * 设置数据类型默认为float
     *
     * @param isFloat true ?float:int
     */
    public void setFloat(boolean isFloat) {
        this.isFloat = isFloat;
    }

    private void init(AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyRatingBar);
        //int srcTop = typedArray.getColor(R.styleable.MyRadioButton_srcTop, -1);

        foregroundColor = typedArray.getColor(R.styleable.MyRatingBar_foregroundColor, foregroundColor);
        backgroundColor = typedArray.getColor(R.styleable.MyRatingBar_backgroundColor, backgroundColor);
        // srcRightDrawable = typedArray.getDrawable(R.styleable.MyRadioButton_srcRight);
        // srcBottomDrawable = typedArray.getDrawable(R.styleable.MyRadioButton_srcBottom);
    }
    int cell_height;
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//
//        if (widthMode == MeasureSpec.EXACTLY) {
//            if (heightMode == MeasureSpec.AT_MOST) {
//                int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//                cell_height = (int) ((widthSize - Math.max(0, getNumStars() - 1) * line_interval) / getNumStars());//最大正方形
//                heightMeasureSpec = MeasureSpec.makeMeasureSpec(cell_height, MeasureSpec.EXACTLY);
//            }
//        }else if (heightMode == MeasureSpec.EXACTLY) {
//            if (widthMode == MeasureSpec.AT_MOST) {
//                cell_height = getMeasuredHeight();
//                int width = (int) (cell_height*getNumStars()+Math.max(0, getNumStars() - 1) * line_interval);
//                widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
//            }
//        }else{
//            if (widthMode == MeasureSpec.AT_MOST) {
//                if (heightMode == MeasureSpec.AT_MOST) {
//                    cell_height = (int) ((getMeasuredWidth() - Math.max(0, getNumStars() - 1) * line_interval) / getNumStars());//最大正方形
//                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(cell_height, MeasureSpec.EXACTLY);
//                }
//            }else if (heightMode == MeasureSpec.AT_MOST) {
//                if (widthMode == MeasureSpec.AT_MOST) {
//                    int width = (int) (getMeasuredHeight()*getNumStars()+Math.max(0, getNumStars() - 1) * line_interval);
//                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
//                }
//            }
//        }
//
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //drawView(canvas);
    }

    private int countMni = 0;//最小取值
    private int countMax = 5;//最大取值
    private int foregroundColor = Color.RED, backgroundColor = Color.LTGRAY;
    private float progress = .8f;
    private float progressMin = 0f;
    private int progressInteger = 0;

    public int getForegroundColor() {
        return foregroundColor;
    }

    public void setForegroundColor(int foregroundColor) {
        this.foregroundColor = foregroundColor;
    }

    public int getBackgroundColor() {
        return backgroundColor;
    }

    @Override
    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    public void setColor(int activateColor, int darkColor) {
        this.foregroundColor = activateColor;
        this.backgroundColor = darkColor;
        postInvalidate();
    }

    public void setProgress(float progress) {
        this.progress = progress;
        postInvalidate();
    }

    /**
     * 设置最小取值 float类型时
     *
     * @param progressMin
     */
    public void setProgressMin(float progressMin) {
        this.progressMin = progressMin;
    }

    /**
     * 设置最小取值 int类型时
     *
     * @param countMni
     */
    public void setCountMni(int countMni) {
        this.countMni = countMni;
    }

    /**
     * int类型的时候取值
     *
     * @return
     */
//    public int getProgressInteger() {
//        progressInteger = (int) Math.max(progress * count, countMni);
//        return progressInteger;
//    }

    public float getProgressFloat() {
        return progress;
    }

//    private float getProgressByState() {
//        if (!isFloat) {//int
//            float a = (float) Math.ceil(progress * count);
//            return Math.max(a, countMni) / count;
//        } else {
//            return Math.max(progress, progressMin);
//        }
//    }

    float line_interval = 0;//间隔

    public void setLine_interval(float line_interval) {
        this.line_interval = line_interval;
        postInvalidate();
    }

    private void drawView(Canvas canvas) {
        Paint mPaint = new Paint();
        mPaint.setAntiAlias(true);
        float rating = getRating();
        //禁用硬件加速
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        //使用离屏绘制
        //int layerID = canvas.saveLayer(0, 0, getWidth(), getHeight(), mPaint, Canvas.ALL_SAVE_FLAG);

        //横向排列的五个星所在的坐标位置gravity：left
        Bitmap backbitmap = null;
        Bitmap frontBitmap = null;
        if (useCustomDrawable) {
            // Bitmap backbitmap = QDBitmapUtil.drawable2Bitmap(backDrawable);
            backbitmap = QDBitmapUtil.drawable2Bitmap(getContext(), backResourceId);
            if (backbitmap != null) {
                backbitmap = QDBitmapUtil.zoomBitmap(backbitmap, cell_height, cell_height);
            }
            frontBitmap = QDBitmapUtil.drawable2Bitmap(getContext(), frontResourceId);
            if (frontBitmap != null) {
                frontBitmap = QDBitmapUtil.zoomBitmap(frontBitmap, cell_height, cell_height);
            }
        }
        //int left = (int) (getMeasuredWidth() / 2f - ((count) * cell + Math.max(0, count - 1) * line_interval) / 2f);
        //遍历绘制五角星
        for (int i = 0; i < getNumStars(); i++) {
            int star_count = (int) Math.floor(rating);
            //int star_count = (int)(rating/getStepSize());
            int star_step_count = (int)((rating-star_count)/getStepSize());
            int bitmap_left,bitmap_top;
            if(rating>i) {
                bitmap_left = (int) (i * cell_height + Math.max(0, star_count - 1) * line_interval);
            }else {
                bitmap_left = (int) (star_count * cell_height + Math.max(0, star_count - 1) * line_interval + star_step_count * getStepSize());
            }
            bitmap_top = getMeasuredHeight() / 2 - cell_height / 2;
            if (!useCustomDrawable) {
                //一个五角星需要10个定点
                //最上面的顶点开始
//                PointF p1 = new PointF(bitmap_left + cell_height / 2f, y1);
//                PointF p2 = new PointF(bitmap_left + cell_height / 2f + cell_height * .14f, y1 + cell_height * .35f);
//                PointF p3 = new PointF(bitmap_left + cell_height / 2f + cell_height * .5f, y1 + cell_height * .35f);
//                PointF p4 = new PointF(bitmap_left + cell_height / 2f + cell_height * .22f, y1 + cell_height * .6f);
//                PointF p5 = new PointF(bitmap_left + cell_height / 2f + cell_height * .35f, y1 + cell_height * 1f);
//                PointF p6 = new PointF(bitmap_left + cell_height / 2f, y1 + cell_height * .72f);
//                PointF p7 = new PointF(bitmap_left + cell_height / 2f - cell_height * .35f, y1 + cell_height * 1f);
//                PointF p8 = new PointF(bitmap_left + cell_height / 2f - cell_height * .22f, y1 + cell_height * .6f);
//                PointF p9 = new PointF(bitmap_left + cell_height / 2f - cell_height * .5f, y1 + cell_height * .35f);
//                PointF p10 = new PointF(bitmap_left + cell_height / 2f - cell_height * .14f, y1 + cell_height * .35f);
//
//                Path path = null;
//                PointF[] points = {p1, p2, p3, p4, p5, p6, p7, p8, p9, p10};
//                for (PointF pointF : points) {
//                    if (path == null) {
//                        path = new Path();
//                        path.moveTo(pointF.x, pointF.y);
//                    } else {
//                        path.lineTo(pointF.x, pointF.y);
//                    }
//                }
//                path.close();
//                mPaint.setColor(backgroundColor);
//                canvas.drawPath(path, mPaint);
//
//                //使用CLEAR作为PorterDuffXfermode绘制的矩形
//                mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//                //设置为在区域内重叠部分绘制
//                RectF rectF = new RectF(0, 0, getMeasuredWidth() * rating, getMeasuredHeight());
//                mPaint.setColor(foregroundColor);
//                canvas.drawRect(rectF, mPaint);
//                //canvas.drawPath(path,mPaint);
//                //最后将画笔去除Xfermode
//                mPaint.setXfermode(null);
//                //还原图层
//                canvas.restoreToCount(layerID);
            } else {
                if (backbitmap != null) {
                    //绘制背景
                    canvas.drawBitmap(backbitmap, bitmap_left, bitmap_top, mPaint);
                }
                //QDLogger.i("frontBitmap index=" + i);
                if (frontBitmap != null) {
                    //绘制前景
                    //canvas.save();
                    Rect rect2 = new Rect(0,0, bitmap_left, getMeasuredHeight());
                    canvas.clipRect(rect2);
                    canvas.drawBitmap(frontBitmap, bitmap_left, bitmap_top, mPaint);
                    //QDLogger.e("frontBitmap index2=" + i);
                    //canvas.restore();
                }
            }
        }
    }

    private boolean canTouch;//是否可触摸改变进度

    public void setCanTouch(boolean canTouch) {
        this.canTouch = canTouch;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!canTouch) {
            return false;
        }
        return super.onTouchEvent(event);
    }
}
